﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace laohan.Common.Common
{
    public partial class API
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    MD5 md5 = new MD5CryptoServiceProvider();

                    byte[] retVal = md5.ComputeHash(file);

                    StringBuilder sb = new StringBuilder();

                    for (int i = 0; i < retVal.Length; i++)
                    {
                        sb.Append(retVal[i].ToString("x2"));
                    }

                    return sb.ToString();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("获取文件MD5哈希值error:" + ex.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strToHash"></param>
        /// <returns></returns>
        public static string GetMD5HashFromString(string strToHash)
        {
            try
            {
                MD5 md5 = new MD5CryptoServiceProvider();

                byte[] bytes = Encoding.UTF8.GetBytes(strToHash);

                bytes = md5.ComputeHash(bytes);

                md5.Clear();

                string ret = "";

                for (int i = 0; i < bytes.Length; i++)
                {
                    ret += Convert.ToString(bytes[i], 16).PadLeft(2, '0');
                }

                return ret;
            }
            catch (Exception ex)
            {
                throw new Exception("获取字符串md4哈希值error：" + ex.Message);
            }
        }
    }
}